class Backend::UsersController < Backend::BaseController
  before_action :set_user, only: [:show, :edit, :update, :destroy, :switch]

  def index
    @search = User.all.ransack(params[:q])
    scope = @search.result
    @users = scope.sorted.page(params[:page])
  end

  def show
  end

  def new
    @user = User.new
  end

  def edit
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to referer_or(backend_users_path), notice: '新增成功'
    else
      flash[:alert] = "新增失败"
      render :new
    end
  end

  def update
    if @user.update(user_params)
      redirect_to referer_or(backend_users_path), notice: '修改成功'
    else
      flash[:alert] = "修改失败"
      render :edit
    end
  end

  def destroy
    if @backend_user.destroy
      redirect_to referer_or(backend_users_path), notice: '删除成功'
    else
      redirect_to referer_or(backend_users_path), alert: '删除失败'
    end
  end

  def switch
    @user.active? ? @user.forbidden! : @user.active!
    redirect_to backend_users_path,notice: @user.active? ?  "用户已解锁": "用户已锁定"
  end


  private

  def set_user
    @user =User.find(params[:id])
  end

  def user_params
    params.require(:user).permit!
  end
end
